package admin

import (
	"ia/apps/admin/dto/oin"
	ooutadmin "ia/apps/admin/dto/oout/admin"
	serviceadmin "ia/apps/admin/service/admin"
	modeladmin "ia/common/model/admin"
	"ia/common/support"
	"ia/common/support/global"

	"github.com/go-sql-driver/mysql"
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
)

func NewAdminOrgRoute() *adminOrgRoute {
	return &adminOrgRoute{}
}

type adminOrgRoute struct{}

func (r *adminOrgRoute) Create(ctx iris.Context, service serviceadmin.AdminOrgService) {
	var (
		code global.Code
		err  error
		in   modeladmin.AdminOrg
	)
	if err = ctx.ReadJSON(&in); err != nil {
		goto ERR
	}
	if err = service.Create(in); err != nil {
		if sqlErr, ok := err.(*mysql.MySQLError); ok {
			if sqlErr.Number == 1062 {
				code = global.CodeDuplicate
			}
		}
		goto ERR
	}
	support.Ok_(ctx)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (r *adminOrgRoute) Edit(ctx iris.Context, service serviceadmin.AdminOrgService) {
	var (
		code global.Code
		err  error
		in   modeladmin.AdminOrg
	)
	if err = ctx.ReadJSON(&in); err != nil {
		goto ERR
	}
	if err = service.Edit(in); err != nil {
		if sqlErr, ok := err.(*mysql.MySQLError); ok {
			if sqlErr.Number == 1062 {
				code = global.CodeDuplicate
			}
		}
		goto ERR
	}
	support.OkTip(ctx, nil)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (r *adminOrgRoute) Delete(ctx iris.Context, service serviceadmin.AdminOrgService) {
	var (
		code   global.Code
		err    error
		idList = make([]int64, 0)
	)
	if err = ctx.ReadJSON(&idList); err != nil {
		goto ERR
	}
	if err = service.DeleteByIdList(idList); err != nil {
		goto ERR
	}
	support.OkTip(ctx, nil)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (r *adminOrgRoute) Table(ctx iris.Context, service serviceadmin.AdminOrgService) {
	var (
		code  global.Code
		err   error
		in    oin.VxeTableIn
		total int64
		rows  = make([]*ooutadmin.AdminOrgOut, 0)
	)
	if err = ctx.ReadQuery(&in); err != nil {
		goto ERR
	}
	if rows, total, err = service.GetTable(in); err != nil {
		goto ERR
	}
	support.VxeTableData(ctx, in.PageSize, in.CurrentPage, total, rows, nil)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (r *adminOrgRoute) List(ctx iris.Context, service serviceadmin.AdminOrgService) {
	var (
		code global.Code
		err  error
		rows = make([]*ooutadmin.AdminOrgOut, 0)
	)
	if rows, err = service.GetList(); err != nil {
		goto ERR
	}
	support.Ok(ctx, rows)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}
